<template>
  <!-- 督办部门负责人 -->
  <!-- 廉洁文化教育负责人 -->
  <!-- 印章管理保管人 -->
  <!--功能：获取单位下所有级下的人员，获取当前单位下的人员-->
  <!--懒加载、懒加载状态、可搜索-->
  <a-select
    v-model="currentValue"
    v-bind="$attrs"
    :label-in-value="labelInValue"
    show-search
    style="width: 100%"
    :filter-option="false"
    v-on="$listeners"
    @popupScroll="(name, e) => (handleScroll(name, e))"
    @search="handleSearch"
    @change="handleChange"
  >
    <a-icon
      v-if="fetching"
      slot="suffixIcon"
      style="color: #096dd9"
      type="loading"
    />
    <a-select-option
      v-for="i in data"
      :key="i.userId"
      :value="i.userId"
    >
      {{ i.name }}
    </a-select-option>
  </a-select>
</template>
<script>
import debounce from 'lodash/debounce'
import { getEmployees } from '@/api/businessAffairs/revenueAndCost'

export default {
    data() {
        this.lastFetchId = 0
        this.handleSearch = debounce(this.handleSearch, 800)
        return {
            data: [],
            baseData: [],
            fetching: false,
            noScroll: true,
            pageNumber: 1,
            totalPages: 1,
            searchVal: '',
        }
    },
    computed: {
        currentValue: {
            get: function () {
                return this.value
            },
            set: function (e) {
                this.$emit('input', e)
                if (e && this.data?.length > 0) {
                    if(this.labelInValue){
                      this.$emit(
                        'getOption',
                        this.data.find((item) => item.userId === e.key)
                      )
                    }else {
                      this.$emit(
                        'getOption',
                        this.data.find((item) => item.userId === e)
                      )
                    }
                }
            }
        }
    },
    props: {
        value: {
            type: [Object, String, Array, Number]
        },
        orgId: {
            type: [Object, String, Array, Number],
            default: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.deptId
        },
        culEdu: {
            type: Boolean,
            default: false
        },
        labelInValue:{
          type: Boolean,
          default: false
        },
    },
    watch: {
        orgId(oldId, newId) {
            if (oldId != newId) {
                this.handleSearch()
            }
        }
    },
    methods: {
        /**
         * 模糊搜索
         */
        handleSearch(value) {
            this.lastFetchId += 1
            this.data = []
            this.fetching = true
            this.searchVal = value
            this.handleEmployees(value, 1)
        },
        handleChange() {
            Object.assign(this, {
                data: this.baseData,
                fetching: false
            })
        },
        /**
         * 下拉滚动加载
         */
        handleScroll(e) {
            let that = this
            const { target } = e
            var total = target.scrollTop + target.offsetHeight
            var scrollHeight = target.scrollHeight
            // this.pageNo是当前页 this.totalPage是总页数
            if (
                total >= scrollHeight - 1 &&
                total < scrollHeight + 1 &&
                that.pageNumber <= that.totalPages &&
                that.noScroll
            ) {
                that.pageNumber += 1
                that.handleEmployees()
            }
            if (that.pageNumber > that.totalPages) {
                that.noScroll = false
                that.pageNumber = 1
            } else {
                that.noScroll = true
            }
        },

        /**
         * 负责人
         * */
        handleEmployees(val, searchPageNumber) {
            this.fetching = true
            const pageNumber = searchPageNumber ? searchPageNumber : this.pageNumber
            let params
            if (this.culEdu) {
                //根据单位获取单位下所有人员
                params = {
                    pageNumber: pageNumber,
                    pageSize: 10,
                    nameLike: this.searchVal,
                    queryPostRelation: true,
                    rootOrgId: this.orgId
                }
            } else {
                //获取该单位下的人员
                params = {
                    pageNumber: pageNumber,
                    pageSize: 10,
                    orgId: this.orgId,
                    nameLike: this.searchVal
                }
            }
            getEmployees(params)
                .then((res) => {
                    if (!val) {
                        this.data = this.data.concat(res.data.list)
                        this.baseData = this.data
                    } else {
                        const fetchId = this.lastFetchId
                        if (fetchId !== this.lastFetchId) {
                            // for fetch callback order
                            return
                        }
                        this.data = res.data.list
                    }
                    this.totalPages = res.data.total
                    this.fetching = false
                })
                .catch(() => {
                    this.fetching = false
                })
        }
    },
    mounted() {
        /**
         * 负责人
         * */
        this.handleEmployees()
    }
}
</script>